package com.manga.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class MangaController {

    @Value("${manga.root}")
    private String rootDir;

    @Autowired
    private FileService fileService;

    @RequestMapping({"/list","/"})
    public String navigation(Model model, @RequestParam(name = "path",required = false) String path){
        model.addAttribute("root",rootDir);
        model.addAttribute("separator", File.separator);
        Path dir;
        if(ObjectUtils.isEmpty(path)){
            dir = Paths.get(rootDir);
        }else{
            dir = Paths.get(rootDir,path);
            List<String> pathList = Arrays.stream(path.split("\\\\+|/+")).filter(StringUtils::hasText).collect(Collectors.toList());
            final StringBuffer sb = new StringBuffer();
            List<String> hrefList = pathList.stream().map(str -> {
                sb.append(str);
                sb.append("/");
                return sb.toString();
            }).collect(Collectors.toList());
            model.addAttribute("hrefs",hrefList);
            model.addAttribute("paths",pathList);
            model.addAttribute("current",path);
        }

        try {
            List<FileInfo> files = Files.list(dir).map(Path::toFile).filter(file -> !file.isHidden()).map(FileInfo::new).collect(Collectors.toList());
            model.addAttribute("list",files);


            return "index";
        } catch (Exception e) {
            model.addAttribute("exception",e);
            return "error";
        }
    }

    @RequestMapping("/read")
    public String read(Model model,@RequestParam(name = "path")String path){
        Path filePath = Paths.get(rootDir,path);
        String name = filePath.getFileName().toString();
        model.addAttribute("title",name);
        model.addAttribute("path",path);
        return "read";
    }
    @RequestMapping("/download")
    public ResponseEntity<Resource> download(@RequestParam String path) throws Exception{
        Path filePath = Paths.get(rootDir,path);
        Resource resource = new UrlResource(filePath.toUri());
        return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/zip")).body(resource);
    }

    @RequestMapping("/read-img")
    public String readImg(Model model,@RequestParam(name = "path")String path){
        Path filePath = Paths.get(rootDir,path);
        String name = filePath.getFileName().toString();
        model.addAttribute("title",name);
        List<String> list = fileService.files(filePath);
        if(CollectionUtils.isEmpty(list)){
            return "read-img";
        }

        list = list.stream().map(str -> path + File.separator + str).collect(Collectors.toList());
        model.addAttribute("list",list);
        return "read-img";
    }
}
